package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUser2Mapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Jt
 * @date 2021/4/12 16:49
 */
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUserRealname> implements ApUserService {

    @Resource
    private ApUser2Mapper apUser2Mapper;

    /**
     * 根据状态查询用户认证列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
//        1.检查参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        检查分页
        dto.checkParam();
//        2.执行分页查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
//        3.封装结果返回
        IPage<ApUserRealname> pageResult = page(page, lambdaQueryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        result.setData(pageResult.getRecords());
        return result;
    }


    /**
     * 根据状态进行审核 (实名认证审核)
     * @param dto
     * @param status 2:审核失败  9:审核成功
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
//        1.检查参数
        if (dto == null || dto.getId()== null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名ID不存在");
        }
//        2.根据id查询实名认证信息(ap_user_realname)
        ApUserRealname realname = getById(dto.getId());

//        3.判断实名认证状态是否为待审核(必须要等与1)
        if (realname == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证数据不存在");
        }
        if (realname.getStatus().intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证状态错误");
        }
//        4.查询实名认证的关联ap_user的用户信息
        ApUser apUser = apUser2Mapper.selectById(realname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关联的用户信息不存在");
        }
//        5.更新实名认证信息(ap_user_realname)
        realname.setCreatedTime(new Date());
        realname.setStatus(status);
//        对原因进行判断
        if (StringUtils.isNotBlank(dto.getMsg())) {
//            说明不为空,设置
            realname.setReason(dto.getMsg());
        }
        updateById(realname);
//        6.如果审核结果为9的话生成自媒体账号,生成作者信息
        if (status.intValue() == AdminConstants.AD_USER_ISSTATUS) {
//            说明是通过的状态 开通自媒体账户
            WmUser wmUser = createWmUser(apUser);
            if (wmUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"创建自媒体用户失败");
            }
//            创建作者信息
            ResponseResult result = createAuthor(apUser,wmUser);
            if (result.getCode() != 0) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"创建作者用户失败");
            }
        }
//        7.当前用户为自媒体人(修改ap_user中flag值)
        apUser.setFlag((short)1);
        apUser2Mapper.updateById(apUser);
        if (!IdCardUtils.checkIdCardInfo(realname.getName(),realname.getIdno())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"姓名或身份证号错误!");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Resource
    private WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
//        根据用户名去查对应的自媒体信息是否存在
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
//        判断
        if (wmUser != null) {
//            说明已经存在,抛异常
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户已经存在");
        }
         wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }

    @Resource
    private ArticleFeign articleFeign;

    private ResponseResult createAuthor(ApUser apUser, WmUser wmUser) {
//        根据userId查询作者的信息
        ApAuthor author = articleFeign.findByUserId(apUser.getId());
        if (author != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者用户已经存在");
        }
         author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        return articleFeign.save(author);
    }

}
